import { ModalForm, ProFormText, ProFormSelect } from '@ant-design/pro-form';
import React, { useImperativeHandle, forwardRef, useState, useRef, useEffect } from 'react';
import { message, Form, Tree } from 'antd';
import request from '@/utils/request';
import apiPath from '@/utils/apiPath.js';
const EditModalFormRef = (props, ref) => {
  const [createModalVisible, handleModalVisible] = useState(false);
  const [currentRow, setCurrentRow] = useState({});
  const [authOptions, setAuthOptions] = useState([]);
  const modalformRef = useRef();
  
  useImperativeHandle(ref, () => ({
    initModal: (row) => {
      if (row.id) {
        modalformRef.current?.setFieldsValue(row);
      } else {
        modalformRef.current?.resetFields();
      }
      console.log(row);
      getAuthOptions();
      setCurrentRow(row);
      handleModalVisible(true);
    }
  }))

  const getAuthOptions = () => {
    request(apiPath.ADMIN_AUTH_HANDLE, {
      method: 'GET',
      params: {
        page: 1,
        per_page: 1000
      },
    })
    .then((res) => {
      setAuthOptions(res.data.list);
    });
  }

  /**
   * 添加节点
   *
   * @param fields
   */
  const handleAdd = async (fields) => {
    let method = 'POST';
    let url = apiPath.ADMIN_AUTH_HANDLE;
    let tips = '';
    
    if (currentRow.id) {
      url = `${url}/${currentRow.id}`;
      method = 'PUT';
      tips = '修改';
    } else {
      tips = '新建';
    }
    const hide = message.loading(`正在${tips}`);
    try {
      await request(url, {
        method,
        data: fields,
      });
      hide();
      props.onReload();
      message.success(`${tips}成功`);
      return true;
    } catch (error) {
      hide();
      message.error(`${tips}失败请重试！`);
      return false;
    }
  };

  return (
    <ModalForm
      title={`${currentRow.id ? '修改' : '新建'}权限点`}
      width="600px"
      formRef={modalformRef}
      layout="horizontal"
      labelCol={{ span: 6 }}
      wrapperCol={{ span: 18 }}
      visible={createModalVisible}
      onVisibleChange={(value) => {
        handleModalVisible(value);
      }}
      onFinish={async (value) => {
        const success = await handleAdd(value);

        if (success) {
          handleModalVisible(false);

          if (actionRef.current) {
            actionRef.current.reload();
          }
        }
      }}
    >
      <ProFormText
        rules={[
          {
            required: true,
            message: "权限名称为必填项",
          },
        ]}
        width="md"
        label="权限名称"
        name="name"
      />
      <ProFormSelect
        rules={[
          {
            required: true,
            message: "请选择类型",
          },
        ]}
        options={[
            { label: '菜单组', value: 1 },
            { label: '菜单', value: 2 },
            { label: '操作点', value: 3 },
        ]}
        width="md"
        label="类型"
        name="type"
      />
      <ProFormSelect
        rules={[
          {
            required: true,
            message: "请选择父节点",
          },
        ]}
        options={authOptions.map(v => {
          return {
            label: v.name, 
            value: v.id
          }
        })}
        width="md"
        label="父节点"
        name="pid"
      />
      <ProFormText
        rules={[
          {
            required: true,
            message: "ACTION_KEY为必填项",
          },
        ]}
        width="md"
        label="ACTION_KEY"
        name="action_key"
      />
      
    </ModalForm>
  )
}
const EditModalForm = forwardRef(EditModalFormRef);
export default EditModalForm;